<template>
  <a-form layout="inline" :model="jenkinsInfo">
    <a-form-item label="url">
      <a-input placeholder="url" v-model:value="jenkinsInfo.Url" />
    </a-form-item>
    <a-form-item label="username">
      <a-input placeholder="username" v-model:value="jenkinsInfo.Username" />
    </a-form-item>
    <a-form-item label="token">
      <a-input-password placeholder="token" v-model:value="jenkinsInfo.Token" />
    </a-form-item>
    <a-form-item>
      <a-button @click="runTask()" :loading="loading">执行</a-button>
    </a-form-item>
    <a-form-item>
      <a-button v-if="loading" @click="stopTask()" danger>放弃治疗！</a-button>
    </a-form-item>

  </a-form>

  <a-typography>
    <pre>{{ content }}</pre>
    <a-back-top />
  </a-typography>
</template>

<script lang="ts" setup>
import { DownloadOutlined } from '@ant-design/icons-vue';
import { computed, reactive, onUnmounted } from 'vue';
import { message } from 'ant-design-vue';
import { EventsOn, EventsOff } from '@/wailsjs/runtime/runtime'
import { ExecJob, GetJenkinsInfo, StopJob } from '@/wailsjs/go/main/App'
import { useStore } from '@/store';

interface JenkinsInfo {
  Url: string,
  Username: string,
  Token: string,
}

const store = useStore();

const loading = computed(() => store.state.loading);
const content = computed(() => store.state.jenkinsLog);
const jenkinsInfo = reactive<JenkinsInfo>({
  Url: '',
  Username: '',
  Token: ''
});

GetJenkinsInfo().then((response: JenkinsInfo) => {
  jenkinsInfo.Url = response.Url
  jenkinsInfo.Username = response.Username
  jenkinsInfo.Token = response.Token
})

EventsOn('logEvent', (data: string) => {
  store.commit('updateJenkinsLog', content.value + data)
})
EventsOn('logEndEvent', () => {
  store.commit('updateLoading', false)
})

const runTask = () => {
  store.commit('updateLoading', true)
  ExecJob({
    Url: jenkinsInfo.Url,
    Username: jenkinsInfo.Username,
    Token: jenkinsInfo.Token,
  }).then(() => {
    message.info('开始构建！')
    store.commit('updateJenkinsLog', '')
  }).catch((err: string) => {
    store.commit('updateLoading', false)
    message.error(err)
  })
}

const stopTask = () => {
  StopJob().then(() => message.info('构建已停止！'))
    .catch((err: string) => {
      message.error(err)
    })
}

onUnmounted(() => {
  EventsOff("logEvent", "logEndEvent")
})

</script>


<style scoped lang="scss">
pre {
  border: none;
  background: none;
}
</style>


